module.exports = app => {
  const router = require('express').Router()
  const mongoose = require('mongoose')
  const Category = mongoose.model('Category')
  const Article = mongoose.model('Article')
  const Hero = mongoose.model('Hero')
  const Item = mongoose.model('Item')
  const Ming = mongoose.model('Ming')
  const Summoner = mongoose.model('Summoner')
  const Ad = mongoose.model('Ad')

/* // 导入新闻列表
  router.get('/news/init', async (req, res) => {
    const parent = await Category.findOne({
      name: '新闻资讯'
    })
    const cats = await Category.find().where({
      parent: parent
    }).lean()
    const newsTitles = ["王者荣耀官方客服招聘", "王者荣耀周年庆表现道具设计大赛现已开启！", "百力滋X王者荣耀 大手笔赠送上百个英雄手办、永久皮肤！", "蓝方惊现自走机甲？为你揭秘蜀地木流牛马的精妙机关", "破浪对决中的战船是……戳开解锁吴地艨艟的“身世之谜”！", "7月22日体验服停机更新公告", "7月22日“演员”惩罚名单", "7月22日外挂专项打击公告", "7月22日净化游戏环境声明及处罚公告", "7月22日全服不停机更新公告", "张飞-虎魄五虎上将限定皮肤即将上架，参与活动领好礼", "【手Q用户专属】李信-一念神魔限时抽免单活动", "李信世冠皮肤即将上架，参与活动赢好礼", "【三分之战 . 集奇兵制胜】活动开启公告", "S20赛季开启，缤纷好礼等你来拿", "7月13日【比赛服】版本更新公告", "2020年王者荣耀世界冠军杯小组赛赛程出炉", "2020年王者荣耀世界冠军杯第二轮选拔赛 加赛及抽签规则", "世冠小组赛抽签仪式6月28日现场直播，小组赛之战一触即发！", "2020年王者荣耀世界冠军杯（KCC）赛事规则"]
    const newsList = newsTitles.map(title => {
      return {
        categories: cats.slice(0).sort((a, b) => Math.random() - .5).slice(0,1),
        title: title
      }
    })
    await Article.deleteMany({})
    await Article.insertMany(newsList)
    res.send(newsList)
  })
*/
  router.get('/news/list', async (req, res) => {
  /*
    const parent = await Category.findOne({
      name: '新闻资讯'
    }).populate({
      path: 'children',
      populate: {
        path: 'newsList'
      }
    }).lean()
  */
    const parent = await Category.findOne({
      name: '新闻资讯'
    })
    // 聚合查询
    const cats = await Category.aggregate([
      { $match: { parent: parent._id } },
      {
        $lookup: {
          from: 'articles',
          localField: '_id',
          foreignField: 'categories',
          as: 'newsList'
        }
      },
      {
        $addFields: {
          newsList: {  $slice: ['$newsList', -5] }
        }
      }
    ])
    cats.unshift({
      name: '热门',
      newsList: await (await Article.find().sort({'_id': -1}).limit(5).populate('categories').lean()).reverse()
    })
    cats.map(cat => {
      cat.newsList.map(news => {
        news.categoryName = cat.name === '热门' ? news.categories[0].name : cat.name
        return news
      })
      return cat
    })
    cats.map(v => v.newsList.reverse())
    res.send(cats)
  })
  router.get('/articles/:id', async (req, res) => {
    const data = await Article.findById(req.params.id).lean()
    data.list =  await Article.find({
      categories: { $in: data.categories },
      createdAt: { $lt: data.createdAt }
    }).sort({_id: -1}).limit(2)
    res.send(data)
  })
 
/*  // 导入英雄数据
  router.get('/hero/init', async (req,res) => {
    await Hero.deleteMany({}) //清空
    let heroData = require('./init/herolist.json')
    heroData.map(async hero => {
      hero.skinName = hero.skin_name.split('|')
      const cat = await Category.findOne({name: hero.hero_type})
      const cat2 = await Category.findOne({name: hero.hero_type2})
      if (!cat2) {
        hero.heroType = [cat]
      } else {
        hero.heroType = [cat, cat2]
      }
      return hero
    })
    await Hero.insertMany(heroData)
    res.send(await Hero.find())
  })
*/
  router.get('/hero/list', async (req, res) => {
    const parent = await Category.findOne({ name: '英雄列表' })
    const cats = await Category.aggregate([
      { $match: { parent: parent._id } },
      {
        $lookup: {
          from: 'heroes',
          localField: '_id',
          foreignField: 'heroType',
          as: 'heroes'
        }
      }
    ])
    const heroes = await Hero.find()
    cats.unshift({
      name: '热门',
      heroes: heroes.sort((a, b) => Math.random() - .5).slice(0,10)
    })
    res.send(cats)
  })

  router.get('/hero/all', async (req, res) => {
    const heroes = await Hero.find()
    const data ={
      name: '全部',
      heroes
    }
    res.send(data)
  })

  router.get('/heroes/:id', async (req, res) => {
    const data = await Hero.findOne({ename: req.params.id})
                           .populate('heroType')
                           .populate('items1.items')
                           .populate('items2.items')
                           .populate('mings')
                           .populate('related.partners.name')
                           .populate('related.weak.name')
                           .populate('related.strong.name')
                           .populate('point.summoner')
    res.send(data)
  })

  router.get('/skins/:id', async (req, res) => {
    const heroData = await Hero.findOne({ename: req.params.id})
    res.send(heroData.skinName)
  })

/*  // 导入装备数据
  router.get('/item/init', async (req, res) => {
    const itemData = require('./init/item.json').map(v => {
      return {
        itemId: v.item_id,
        name: v.item_name,
        icon: `https://game.gtimg.cn/images/yxzj/img201606/itemimg/${v.item_id}.jpg`
      }
    })
    Item.deleteMany()
    Item.insertMany(itemData)
    res.send(await Item.find())
  })
*/

/*  // 导入铭文数据
  router.get('/ming/init', async (req, res) => {
    const mingData = require('./init/ming.json')
    await Ming.deleteMany({})
    await Ming.insertMany(mingData)
    res.send(await Ming.find())
  })
*/

/*  // 导入召唤师技能数据
  router.get('/summoner/init', async (req, res) => {
    const summonerData = require('./init/summoner.json')
    summonerData.map(v => v.summoner_icon = `https://game.gtimg.cn/images/yxzj/img201606/summoner/${v.summoner_id}.jpg`)
    await Summoner.deleteMany({})
    await Summoner.insertMany(summonerData)
    res.send(await Summoner.find())
  })
*/

/*  // 导入英雄页面详细数据
  router.get('/herodetail/init', async (req, res) => {
    const data = require('./init/hero_detail.json')
    data.map(h => {
      h.items1 && h.items1.items.map(async (v, i) => h.items1.items[i] = await Item.findOne({itemId: v}))
      h.items2 && h.items2.items.map(async (v, i) => h.items2.items[i] = await Item.findOne({itemId: v}))
      h.point && h.point.summoner.map(async (v, i) => h.point.summoner[i] = await Summoner.findOne({summoner_id: v}))
      h.mings && h.mings.map(async (v, i) => h.mings[i] = await Ming.findOne({ming_id: v}))
      h.related && Object.keys(h.related).forEach(cat => h.related[cat].map(async i => i.name = await Hero.findOne({ename: i.name})))
    })
    data.map(async h => await Hero.updateOne({ename: h.ename}, h))
    res.send(await Hero.find())
  })
*/
  
  router.get('/ads', async (req, res) => {
    const data = await Ad.find()
    res.send(data)
  })

  app.use('/web/api', router)
}
